package com.catcher.infobackup.xyf;


import android.app.Activity;
import android.content.Context;
import android.content.IntentFilter;
import android.hardware.usb.UsbManager;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.storage.StorageManager;
import android.os.storage.VolumeInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Array;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import java.text.SimpleDateFormat;
import java.util.Date;

import com.catcher.infobackup.R;


public class XYFMainActivity extends Activity {

    Button btStore ,btRestore,btRefresh;
    TextView tv,tv1,tv2;
    //备份
    ArrayList<String> mPhotos = new ArrayList<>();
    ArrayList<String> mAudios = new ArrayList<>();
    ArrayList<String> mVideos = new ArrayList<>();
    ArrayList<String> mFiles = new ArrayList<>();

    //恢复
    ArrayList<String> mRPhotos = new ArrayList<>();
    ArrayList<String> mRAudios = new ArrayList<>();
    ArrayList<String> mRVideos = new ArrayList<>();
    ArrayList<String> mRFiles = new ArrayList<>();

    ArrayList<String> mBackupList = new ArrayList<>();

    boolean isStoreing = false;
    boolean isReStoreing = false;
    FileOpreateUtils mFOU = new FileOpreateUtils();
    String mData;
    ZipUtils mZipUtils = new ZipUtils();

    //恢复路径
    private final String RESTORE_PATH_PHOTO = "/ebenBackup/Photo/a.txt";
    private final String RESTORE_PATH_AUDIO = "/ebenBackup/AUDIO/a.txt";
    private final String RESTORE_PATH_VIDEO = "/ebenBackup/VIDEO/a.txt";
    private final String RESTORE_PATH_FILES = "/ebenBackup/FILE/a.txt";

    ListView lv;
    ArrayAdapter adpter;
    String selected = "";
    private UsbReceiver mUsbReceiver;
    Handler myHandler = new Handler(Looper.getMainLooper()) {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    if(null != msg.obj) {
                        tv.setText(msg.obj.toString());
                    }

                    break;
                case 2:
                    if(null != msg.obj) {
                        tv1.setText(msg.obj.toString());
                    }
                    break;
                case 3:
                    mPhotos.clear();
                    mAudios.clear();
                    mVideos.clear();
                    mFiles.clear();
                    makeDir(true);
                    tv1.setText(R.string.create_store_path);

                    new Thread(new Runnable() {
                        @Override
                        public void run() {

                            Message msg1 = myHandler.obtainMessage();
                            msg1.what = 1;
                            msg1.obj = getResources().getString(R.string.data_storeing);
                            msg1.sendToTarget();

                            startScan(true);
                            startCopy(true);
                            isStoreing = false;
                            Message msg = myHandler.obtainMessage();
                            msg.what = 1;
                            msg.obj = getResources().getString(R.string.data_store_complete);;
                            msg.sendToTarget();
                            updateAviableList();

                        }
                    }).start();

                    break;
                case 4:
                    updateUsbStatus();
                    break;

                case 5:
                    Toast.makeText(getApplicationContext(), msg.obj.toString(),
                            Toast.LENGTH_SHORT).show();
                    break;

            }

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.xyfactivity_main);
        initView();
        initClick();
        updateUsbStatus();
    }
    public static final String ACTION_EBEN_USB_STATUS_CHANGED = "action.eben.usb.status.changed";
    private void initView(){
        lv = (ListView)findViewById(R.id.lv);
        btStore = (Button)findViewById(R.id.scan);
        btRestore = (Button)findViewById(R.id.recover);
        btRefresh = (Button)findViewById(R.id.refresh);
        tv = (TextView)findViewById(R.id.info);
        tv1 = (TextView)findViewById(R.id.dir);
        tv2 = (TextView)findViewById(R.id.restoreList);
        IntentFilter usbFileter = new IntentFilter(
                UsbManager.ACTION_USB_STATE);
        usbFileter.addAction(ACTION_EBEN_USB_STATUS_CHANGED);
        mUsbReceiver = new UsbReceiver(mMountCallBack);
        registerReceiver(mUsbReceiver, usbFileter);
        
    }
    @Override
    public void onDestroy() {
    	  if(mUsbReceiver!=null){
              unregisterReceiver(mUsbReceiver);
              mUsbReceiver = null;
          }
    }
    private void initClick(){
        adpter = new ArrayAdapter<>(this,R.layout.backup_layout_item,R.id.backup,mBackupList);
        lv.setAdapter(adpter);

        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                tv2.setText(mBackupList.get(position));
                selected = mBackupList.get(position);
            }
        });


        btRestore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                File target = new File(getUSBpath(XYFMainActivity.this)+"/catchBackup/EBEN_BACKUP/");

                if(!target.exists()){
                    Toast.makeText(getApplicationContext(), getString(R.string.no_restroe_file),
                            Toast.LENGTH_SHORT).show();
                    return;
                }

                if(isReStoreing) {
                    Toast.makeText(getApplicationContext(), getString(R.string.date_restoreing),
                            Toast.LENGTH_SHORT).show();
                    return;
                }

                notifyUI(2,getString(R.string.create_restore_path));

                mRPhotos.clear();
                mRAudios.clear();
                mRVideos.clear();
                mRFiles.clear();

                new Thread(new Runnable() {
                    @Override
                    public void run() {


                        notifyUI(1, getString(R.string.date_restoreing));
                        String s = "";
                        startScan(false);
                        if(!selected.equals("")) {
                            startCopy(false);
                            s = getString(R.string.data_restore_complete)+"图片"+mRPhotos.size()+"张"+"视频"+mRVideos.size()+"部"
                                    +"音频"+mRAudios.size()+"首"+"文件"+mRFiles.size()+"个";
                        }else {
                            s = "没有可用数据";
                            notifyUI(2,s);
                        }

                        notifyUI(1,s);

                        isReStoreing = false;

                    }
                }).start();
            }
        });

        btStore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                File target = new File(getUSBpath(XYFMainActivity.this)+"/catchBackup/EBEN_BACKUP/");

                if(target.exists()){
                    Toast.makeText(getApplicationContext(), getString(R.string.continue_backup_working),
                            Toast.LENGTH_SHORT).show();
                    return;
                }

                if(isStoreing) {
                    Toast.makeText(getApplicationContext(), getString(R.string.data_storeing),
                            Toast.LENGTH_SHORT).show();
                    return;
                }
                Message msg = myHandler.obtainMessage();
                msg.what = 3;
                msg.sendToTarget();
            }
        });

        btRefresh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Message msg1 = myHandler.obtainMessage();
                msg1.what = 4;
                msg1.sendToTarget();
            }
        });

    }

    private void updateUsbStatus(){

        File target = new File(getUSBpath(XYFMainActivity.this));
        if(!target.exists()){
            tv.setText(R.string.no_usb);
            btStore.setEnabled(false);
            btRestore.setEnabled(false);
        }else{
            updateAviableList();
            tv.setText(R.string.get_usb);
            btStore.setEnabled(true);
            btRestore.setEnabled(true);
        }
    }

    private void updateAviableList(){
        File target1 = new File(getUSBpath(XYFMainActivity.this)+"/catchBackup/EBEN_BACKUP/");
        mBackupList.clear();
        if(target1.exists()){

            File[] f = target1.listFiles();

            if (f == null) {
                Log.d("xyf","files == null");
                return;
            }
            String fileName = "";
            //遍历当前文件下的所有文件
            for (final File file : f) {
                if (file.isDirectory()) {
                    mBackupList.add(file.getName());
                    selected = file.getName();
//                    Toast.makeText(getApplicationContext(), file.getName(),
//                            Toast.LENGTH_SHORT).show();
//                    try {
//                        Thread.sleep(300);
//                    } catch (InterruptedException e) {
//                        e.printStackTrace();
//                    }
                }
            }

        }
//        adpter.notifyDataSetChanged();
    }


    private void makeDir(boolean flag){
        final String USB = getUSBpath(XYFMainActivity.this);
        File target1  = Environment.getExternalStorageDirectory();
        final String ROOT = target1.getAbsolutePath();

        if(flag) {

            getCurTime();
            File f = new File(USB + "/catchBackup/EBEN_BACKUP/" + mData + "/a.txt");
            boolean b = f.getParentFile().mkdirs();

            String obj = "数据将备份到你的U盘" + "/catchBackup/EBEN_BACKUP" + mData + "/目录下 result === " + b;
            notifyUI(2,obj);


            File f1 = new File(USB + "/catchBackup/EBEN_BACKUP/" + mData + "/Photo/" + "/a.txt");
            f1.getParentFile().mkdirs();

            File f2 = new File(USB + "/catchBackup/EBEN_BACKUP/" + mData + "/Video/" + "/a.txt");
            f2.getParentFile().mkdirs();

            File f3 = new File(USB + "/catchBackup/EBEN_BACKUP/" + mData + "/Audio/" + "/a.txt");
            f3.getParentFile().mkdirs();

            File f4 = new File(USB + "/catchBackup/EBEN_BACKUP/" + mData + "/File/" + "/a.txt");
            f4.getParentFile().mkdirs();
        }
        else{

            File f = new File(ROOT + "/catchBackup/EBEN_BACKUP/"+"/a.txt");
            boolean b = f.getParentFile().mkdirs();

            String obj = "数据将备份到你的内存" + "/catchBackup/EBEN_BACKUP" + "/目录下 创建结果 ： " + b;
            notifyUI(2,obj);


            File f1 = new File(USB + RESTORE_PATH_PHOTO);
            f1.getParentFile().mkdirs();

            File f2 = new File(USB + RESTORE_PATH_AUDIO);
            f2.getParentFile().mkdirs();

            File f3 = new File(USB + RESTORE_PATH_VIDEO);
            f3.getParentFile().mkdirs();

            File f4 = new File(USB + RESTORE_PATH_FILES);
            f4.getParentFile().mkdirs();
        }
    }

    public void recursionFile(File dir,boolean flag) throws InterruptedException {
        //得到某个文件夹下所有的文件

        File[] files = dir.listFiles();
        //文件为空
        if (files == null) {
            Log.d("xyf","files == null");
            return;
        }
        String fileName = "";
        //遍历当前文件下的所有文件
        for (final File file : files) {
            //如果是文件夹

            fileName = file.getName().toLowerCase();
            if (file.isDirectory()) {
                //则递归继续遍历该文件夹
                recursionFile(file,flag);
            } else { //如果不是文件夹 则是文件
                Thread.sleep(50);
                if (fileName.endsWith(".jpg") || fileName.endsWith(".jpeg") || fileName.endsWith(".png")
                        || fileName.endsWith(".gif") || fileName.endsWith(".bmp")) {
                      if(flag) {
                          mPhotos.add(file.getAbsolutePath());
                      }else{
                          mRPhotos.add(file.getAbsolutePath());
                      }
                      notifyUI(1,"found file "+file.getAbsolutePath());

                }else if(fileName.endsWith(".mp3") || fileName.endsWith(".wma") || fileName.endsWith(".ogg")
                        || fileName.endsWith(".flac")|| fileName.endsWith(".ape") || fileName.endsWith(".aac")){
                        Log.d("xxx","found audio name ===== "+file.getName());
                        if(flag) {
                            mAudios.add(file.getAbsolutePath());
                        }else{
                            mRAudios.add(file.getAbsolutePath());
                         }
                        notifyUI(1,"found file "+file.getAbsolutePath());

                }else if(fileName.endsWith(".3gp") || fileName.endsWith(".rmvb") || fileName.endsWith(".mkv")
                        || fileName.endsWith(".mp4")|| fileName.endsWith(".wmv")|| fileName.endsWith(".mov")
                        || fileName.endsWith(".avi")){

                        if(flag) {
                            mVideos.add(file.getAbsolutePath());
                        }else{
                            mRVideos.add(file.getAbsolutePath());
                        }
                        notifyUI(1,"found file "+file.getAbsolutePath());

                }else if(fileName.endsWith(".word") || fileName.endsWith(".ppt") || fileName.endsWith(".pdf")
                        || fileName.endsWith(".txt")|| fileName.endsWith(".excel")){

                        if(flag) {
                            mFiles.add(file.getAbsolutePath());
                        }else{
                            mRFiles.add(file.getAbsolutePath());
                        }
                        notifyUI(1,"found file "+file.getAbsolutePath());
                }

            }
        }
    }


    private void getCurTime(){
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd_HHmmss");
        Date curDate = new Date(System.currentTimeMillis());//获取当前时间
        mData = formatter.format(curDate);
    }

    private void notifyUI(int wh, String msg){
        Message message = myHandler.obtainMessage();
        message.what = wh;
        message.obj = msg;
        message.sendToTarget();
    }

    public ArrayList<String> startScan(boolean flag) {
        File dir = Environment.getExternalStorageDirectory();

        if(!flag){
//            if(selected.equals("")){
//                notifyUI(5,"请选择一个可恢复的文件");
//                return null;
//            }
//            dir = new File(getUSBpath(XYFMainActivity.this)+"/catchBackup/EBEN_BACKUP/"+selected);
            dir = new File(getUSBpath(XYFMainActivity.this)+"/catchBackup/EBEN_BACKUP/");
            if(null == dir)
            {
                notifyUI(5,"没有找到可恢复的文件");
                return null;
            }
        }

        //调用遍历所有文件的方法
        try {
            recursionFile(dir,flag);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //返回文件路径集合
        return null;
    }

    private void startCopy(boolean flag){
        File target = new File(getUSBpath(XYFMainActivity.this));
        File target1  = Environment.getExternalStorageDirectory();
        final String USB = target.getAbsolutePath();
        final String ROOT = target1.getAbsolutePath();

        int pNum = 0, aNum = 0, vNum = 0, fNum = 0;
        if(target.exists()) {

            if(flag) {
                isStoreing = true;
                for (String s : mPhotos) {
                    File photo = new File(s);
                    pNum++;
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    int r = mFOU.copyfile(photo, new File(USB + "/catchBackup/EBEN_BACKUP/" + mData + "/Photo/" + photo.getName()), false);
                    String msg = "";
                    if(r == 0) {
                        msg = "备份图片:" + photo.getAbsolutePath() + "第" + pNum + "张";
                    }else{
                        msg = "备份失败"+"第" + pNum + "张" + "errorCode ====="+r;
                    }
                    notifyUI(1,msg);
                }

                for (String s : mAudios) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    File audio = new File(s);
                    int r = mFOU.copyfile(audio, new File(USB + "/catchBackup/EBEN_BACKUP/" + mData + "/Audio/" + audio.getName()), false);
                    aNum++;
                    String msg = "";
                    if(r == 0) {
                        msg = "备份音频:"+audio.getAbsolutePath()+"第"+aNum+"首";
                    }else{
                        msg = "备份失败"+"第" + pNum + "张"+ "errorCode ====="+r;
                    }
                    notifyUI(1,msg);
                }

                for (String s : mVideos) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    File video = new File(s);
                    int r = mFOU.copyfile(video, new File(USB + "/catchBackup/EBEN_BACKUP/" + mData + "/Video/" + video.getName()), false);
                    vNum++;
                    String msg = "";

                    if(r == 0) {
                        msg = "备份视频:"+video.getAbsolutePath()+"第"+vNum+"部";
                    }else{
                        msg = "备份失败"+"第" + pNum + "张"+ "errorCode ====="+r;
                    }
                    notifyUI(1,msg);
                }

                for (String s : mFiles) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    File file = new File(s);
                    int r = mFOU.copyfile(file, new File(USB + "/catchBackup/EBEN_BACKUP/" + mData + "/File/" + file.getName()), false);
                    fNum++;
                    String msg = "";
                    if(r == 0) {
                        msg = "备份文件:"+file.getAbsolutePath()+"第"+fNum+"个";
                    }else{
                        msg = "备份失败"+"第" + pNum + "张"+ "errorCode ====="+r;
                    }
                    notifyUI(1,msg);
                }
            }else{
                isReStoreing = true;

                if(mRPhotos.size() >0 || mRAudios.size() > 0 || mRVideos.size() > 0 || mRFiles.size() > 0){
                    notifyUI(2,"数据将恢复到内存中/catchBackup/EBEN_BACKUP/"+selected+"目录下");
                }

                for (String s : mRPhotos) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    File photo = new File(s);
                    pNum++;
                    int r = mFOU.copyfile(photo, new File(ROOT + "/catchBackup/EBEN_BACKUP/" + selected + "/Photo/" + photo.getName()), false);
                    String msg = "";
                    if(r == 0) {
                        msg = "恢复图片:" + photo.getAbsolutePath() + "第" + pNum + "张";
                    }else{
                        msg = "恢复失败"+"第" + pNum + "张" + "errorCode ====="+r;
                    }
                    notifyUI(1,msg);
                }

                for (String s : mRAudios) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    File audio = new File(s);
                    int r = mFOU.copyfile(audio, new File(ROOT + "/catchBackup/EBEN_BACKUP/" + selected + "/Audio/" + audio.getName()), false);
                    aNum++;
                    String msg = "";
                    if(r == 0) {
                        msg = "备份音频:"+audio.getAbsolutePath()+"第"+aNum+"首";
                    }else{
                        msg = "备份失败"+"第" + pNum + "张"+ "errorCode ====="+r;
                    }
                    notifyUI(1,msg);
                }

                for (String s : mRVideos) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    File video = new File(s);
                    int r = mFOU.copyfile(video, new File(ROOT + "/catchBackup/EBEN_BACKUP/" + selected + "/Video/" + video.getName()), false);
                    vNum++;
                    String msg = "";

                    if(r == 0) {
                        msg = "备份视频:"+video.getAbsolutePath()+"第"+vNum+"部";
                    }else{
                        msg = "备份失败"+"第" + pNum + "张"+ "errorCode ====="+r;
                    }
                    notifyUI(1,msg);

                }

                for (String s : mRFiles) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    File file = new File(s);
                    int r = mFOU.copyfile(file, new File(ROOT + "/catchBackup/EBEN_BACKUP/" + selected + "/File/" + file.getName()), false);
                    fNum++;
                    String msg = "";
                    if(r == 0) {
                        msg = "备份文件:"+file.getAbsolutePath()+"第"+fNum+"个";
                    }else{
                        msg = "备份失败"+"第" + pNum + "张"+ "errorCode ====="+r;
                    }
                    notifyUI(1,msg);
                }

            }
        }
    }

    public class FileOpreateUtils {
        /**
         *
         * @param fromFile 被复制的文件
         * @param toFile 复制的目录文件
         * @param rewrite 是否重新创建文件
         *
         * <p>文件的复制操作方法
         */
        public int copyfile(File fromFile, File toFile,Boolean rewrite ){

            if(!fromFile.exists()){
                return 1;
            }
            if(!fromFile.isFile()){
                return 2;
            }
            if(!fromFile.canRead()){
                return 3;
            }
            if(!toFile.getParentFile().exists()){
                boolean b = toFile.getParentFile().mkdirs();
                if(!b)
                notifyUI(2,"路径创建失败");
            }
            if(toFile.exists() && rewrite){
                toFile.delete();
            }
            try {
                FileInputStream fosfrom = new FileInputStream(fromFile);
                FileOutputStream fosto = new FileOutputStream(toFile);

                byte[] bt = new byte[1024];
                int c;
                while((c=fosfrom.read(bt)) > 0){
                    fosto.write(bt,0,c);
                }
                //关闭输入、输出流
                fosfrom.close();
                fosto.close();
                return 0;
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return 4;
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return 5;
            }
        }
    }

    /**
     * 挂载监听
     */
    private IController.MountCallBack mMountCallBack = new IController.MountCallBack() {

        @Override
        public void refreshMountState(final String path, final boolean state) {
        	myHandler.post(new Runnable(){
				@Override
				public void run() {
					notifyUI(5,"refreshMountState call in path = "+path+"state = "+state);
//					onRefreshMountState(path, state);
				}});
        }

		@Override
		public void onUsbStateChanged(boolean connected, boolean configuared) {
//			ControllerImpl.this.onUsbStateChanged(connected, configuared);
			notifyUI(5,"onUsbStateChanged call in connected = "+connected+"configuared = "+configuared);
		}
        
    };
    
    
    public  String getUSBpath(Context ctx) {
        StorageManager mStorageManager = (StorageManager) ctx.getSystemService(Context.STORAGE_SERVICE);
        final List<VolumeInfo> volumes = mStorageManager.getVolumes();
        Collections.sort(volumes, VolumeInfo.getDescriptionComparator());

        Log.w("xxx", "StorageSettings, refresh, volumes.size() == " + volumes.size());
        for (VolumeInfo vol : volumes) {

            if (vol.getType() == VolumeInfo.TYPE_PUBLIC) {
                Log.w("xxx", "111StorageSettings, refresh, external vol.getPath() == " + vol.getPath());
//                Toast.makeText(getApplicationContext(), "1111"+vol.getPath(),
//                        Toast.LENGTH_SHORT).show();
                if (vol.getDisk().isUsb()) {
                    if (vol.getPath() == null) {
//                    	 Log.w("xxx", "222StorageSettings, refresh, external vol.getPath() == " + vol.getPath());
                        return "null";
                    }
//                    Toast.makeText(getApplicationContext(), "2222"+vol.getPath().getPath(),
//                            Toast.LENGTH_SHORT).show();
                    Log.w("xxx", "333StorageSettings, refresh, external vol.getPath() == " + vol.getPath());
//                    Utils.PATH_UDISK = vol.getPath().getPath();
//                    Constants.U_FILE_FLAG = Utils.PATH_UDISK;U盘断开连接	
//                    StorageUtil.setUDiskPath(vol.getPath().getPath());
//                    StorageUtil.setUDiskState(getState(ctx, vol.getPath().getPath()).equals("mounted"));
                    //Log.w("liweichao", "Utils.PATH_udisk == " + Utils.PATH_UDISK);
                    //Log.w("liweichao", "Utils.PATH_udisk state is  " + mStorageManager.getVolumeState(Utils.PATH_UDISK));
                    return vol.getPath().getPath();
                }
            }
        }
        return "null";
    }
    
    
    public  String getStoragePaths(String keyword) {
        String targetpath = "";
        Class<?> storageVolumeClazz = null;
        StorageManager  mStorageManager = (StorageManager) getSystemService(Context.STORAGE_SERVICE);
        try {
            storageVolumeClazz = Class.forName("android.os.storage.StorageVolume");
            Method getVolumeList = mStorageManager.getClass().getMethod("getVolumeList");
            Method getPath = storageVolumeClazz.getMethod("getPath");
            Object result = getVolumeList.invoke(mStorageManager);
            final int length = Array.getLength(result);
            Method getUserLabel = storageVolumeClazz.getMethod("getUserLabel");

            for (int i = 0; i < length; i++) {
                Object storageVolumeElement = Array.get(result, i);
                String userLabel = (String) getUserLabel.invoke(storageVolumeElement);
                if(i > 0 && !userLabel.contains("SD卡")){
                    String path = (String) getPath.invoke(storageVolumeElement);
                    targetpath = path;
                }
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return targetpath ;
    }

}